
import time, datetime
from pymongo import MongoClient
from bson import ObjectId
import re

dbs = {
    "mongo-local": {
        "host": "127.0.0.1",
        "port": 27017,
        "username": "brotherbaby",
        "password": "q1w2e3r4",
        "authSource": "mytest"
    },
    # "mongo-dev": {
    #     "host": "127.0.0.1",
    #     "port": 27017,
    #     "username": "brotherbaby",
    #     "password": "q1w2e3r4",
    #     "authSource": "mytest"
    # },
}

mongodb_ins = MongoClient(**dbs["mongo-local"]).mytest


def do_biz():
    pps = mongodb_ins.XHHK_ProblemPatInfo.find({
        "$or": [{"id_number_mismatch": 1, "xhhk_id_number": {"$in": ["", None, "-", "未提供", " "]}},
                {"gender_mismatch": 1, "his_gender": {"$ne": '9'}, "xhhk_gender": {"$in": ["", None, "-", "未提供", " "]}}
                ]
    })

    # compare....
    i = 1
    for pp in pps:
        mc = mongodb_ins.XHHK_MedicalCard.find_one({"app_id": ObjectId("5b77eb906615b700151dc07d"),
                                           "card_id": pp.get("card_id"), "obsoleted": False})
        if not (mc and mc.get("patient_id")):
            continue
        pat = mongodb_ins.XHHK_Patient.find_one({"_id": mc.get("patient_id")})
        if not pat:
            continue
        up_id_number, up_gender = None, None
        if pp.get("id_number_mismatch") == 1:
            hisid_number = confirm_data(pp.get("his_id_number"), "id_number")
            if pat.get("id_number") in ["", None, "-", "未提供", " "] and hisid_number:
                up_id_number = hisid_number
        if pp.get("gender_mismatch") == 1:
            hisgender = confirm_data(pp.get("his_gender"), "gender")
            if pat.get("gender") in ["", None, "-", "未提供", " "] and hisgender:
                up_gender = hisgender
        set_p = {}
        if up_id_number:
            set_p["id_number"] = up_id_number
        if up_gender:
            set_p["gender"] = up_gender
        if set_p:
            mongodb_ins.XHHK_Patient.update_one({"_id": pat.get("_id")}, {"$set": set_p})
        print("=========: %d", i)
        i += 1
    print("finished.")

def confirm_data(dat, dat_type):
    if dat_type == "id_card":
        dat = dat.strip()
        if len(dat) != 18:
            return ""
        regex_str = r"[1-9]\d{5}(19[0-9]{2}|20[0-9]{2})((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
        if not re.match(regex_str, dat):
            return ""
    elif dat_type == "gender":
        if dat not in [1, 2, "1", "2"]:
            return ""
        dat = int(dat)
    return dat

def main():
    do_biz()

if __name__ == '__main__':
    main()
